<template>
  <n-form-item label="品牌形象跳转" path="none" class="creative-component-form-item" :show-require-mark="true"
    :rule="formRule.none">
    <div class="flex-1">
      <n-radio-group v-model:value="creativor.brandType" :disabled="optionalInLoad" @update:value="changeBrandType">
        <!-- 如果是视频号的就不展示 品牌简介页/品牌形象 -->
        <n-radio-button v-if="mainOptionalAuth[4]" :value="4" label="品牌简介页" :disabled="optionalInLoad" />
        <n-radio-button v-if="mainOptionalAuth[3]" :value="3" label="品牌形象" :disabled="optionalInLoad" />
        <n-radio-button v-if="mainOptionalAuth['WECHAT_CHANNELS']" value="WECHAT_CHANNELS" label="视频号"
          :disabled="optionalInLoad">
          <div class="flex items-center wechat-channels-button" @click.native="showSetChannel">
            视频号
            <n-icon size="14">
              <SettingFilled></SettingFilled>
            </n-icon>
            <div class="tooltip" v-if="creativor.brandType == 'WECHAT_CHANNELS'">
              请配置视频号，共有{{ wxChannelConfigStatus.all }}个账户已配置{{ wxChannelConfigStatus.seted }}个账户
              <div class="arrow-wrapper">
                <div class="arrow"></div>
              </div>
            </div>
            <!-- <n-tooltip placement="top" trigger="manual" :show="creativor.brandType == 'WECHAT_CHANNELS'">
              <template #trigger>
                <n-icon size="14">
                  <SettingFilled></SettingFilled>
                </n-icon>
              </template>
请配置视频号，共有{{ wxChannelConfigStatus.all }}个账户已配置{{ wxChannelConfigStatus.seted }}个账户
</n-tooltip> -->
          </div>
        </n-radio-button>
      </n-radio-group>
      <div class="mt-10" v-if="creativor.brandType !== 'WECHAT_CHANNELS'">
        <n-select clearable :loading="optionalInLoad" @update:value="changeValue" :value="form.brand_image_id"
          filterable :options="optional" :render-label="renderLabel" placeholder="请选择简介页/品牌形象"
          :fallback-option="() => ({ label: form.brand_name, value: form.brand_image_id })">
          <template #action><span class="text-helper">找不到品牌简介页/品牌形象?</span><span
              class="ml-5 link-color cursor-pointer font-12" @click="toUploadBrand">去上传</span></template>
        </n-select>

      </div>
    </div>
  </n-form-item>

  <n-modal v-model:show="uploadModal.show" :style="{ width: '600px' }" preset="card" title="上传头像昵称"
    :mask-closable="false">
    <brandUpload :key="uploadModal.show ? 1 : 0" :rules="rules.media" ref="uploadManageRef"></brandUpload>
    <template #footer>
      <div class="text-right">
        <n-button type="primary" @click="submitBrand" :loading="uploadModal.loading">确定</n-button>
      </div>
    </template>
  </n-modal>


  <n-modal v-model:show="setChannelModal.show" :style="{ width: '600px' }" preset="card" title="配置视频号"
    :mask-closable="false">
    <n-scrollbar style="height: 400px;">
      <div v-for="item in accounts" class="flex items-center" style="margin-top: 10px;">

        <n-button @click="checkAccount(item)" style="width: 120px;">
          {{ item.accountCode }}
          <template #icon>
            <n-icon color="green" v-if="item.wechatChannels.id">
              <CheckCircleFilled />
            </n-icon>
          </template>
        </n-button>

        <n-select @click="checkAccount(item)" :fallback-option="() => wechatChannelsFallBackOption(item)"
          style="margin-left: 12px;" :value="item.wechatChannels.id" clearable filterable
          :options="item.wechatChannels.optional || []" @update:value="updateWechatChannels">
          <template #action><span class="text-helper">只显示已授权的视频号</span>
            <span class="ml-5 link-color cursor-pointer font-12" @click="toAuthChannel">视频号授权</span>
            <span @click="() => getWechatChannelOptional(item)" class="ml-5 link-color cursor-pointer font-12">刷新</span>
          </template>
        </n-select>
      </div>
    </n-scrollbar>
    <template #footer>
      <div class="text-right">
        <n-button type="primary" @click="closesetChannelModal">确定</n-button>
      </div>
    </template>
  </n-modal>




  <n-modal v-model:show="setProfilesModal.show" :style="{ width: '600px' }" preset="card" title="新建品牌简介页"
    :mask-closable="false">
    <x-form ref="profileformRef" v-model:model="setProfilesModal.form" :rules="setProfilesModal.rules"
      label-placement="top" label-width="120">
      <n-form-item path="headImageId" :show-label="false" label="头像">
        <!-- {{rules}} -->
        <upload @finish="finishProfileImage" :accept="`image/*`" ref="uploadRef" style="width: 200px;"
          :rules="rules.media" :params="profilesParams" :key="setProfilesModal.show ? 1 : 0"
          :value="{ meta_type: '', media_url: '' }">
        </upload>
      </n-form-item>
      <n-form-item label="名称" path="profileName">
        <n-input v-model:value="setProfilesModal.form.profileName" :maxlength="12" :show-count="true"
          :minlength="2"></n-input>
      </n-form-item>
      <n-form-item label="详细描述" path="description">
        <n-input v-model:value="setProfilesModal.form.description" :maxlength="120" type="textarea"
          :show-count="true"></n-input>
      </n-form-item>
    </x-form>
    <template #footer>
      <div class="text-right">
        <n-button type="primary" @click="closesetProfilesModal">确定</n-button>
      </div>
    </template>
  </n-modal>



</template>

<script setup lang="ts">
import { computed, onBeforeMount, reactive, ref, toRef, unref, watch, h, nextTick } from 'vue';
import { useStore } from '@/store';
import Component from '@/store/modules/adv/component';
import { NSwitch, NRadioGroup, NRadioButton, NRadio, NModal, NButton, NSelect, NImage, NIcon, NTooltip, NInput, NScrollbar } from 'naive-ui';
import ThumbnailSelect from './thumbnail-select.vue';
import UploadManage from './upload-mange.vue';
import upload from './upload.vue';
import { getAdBrandList, getProfileList, getWechatChannel, addProfile } from '@/api/intelligent';
import { CheckCircleFilled, SettingFilled } from '@vicons/antd';
import brandUpload from './brand-upload.vue';
import { unique } from '@/utils';
import {
  NFormItem,
} from 'naive-ui'
import { count } from '@/utils/text';
import { XForm } from '@/components';
const store = useStore();
const adv = computed(() => store.state.adv.modal);
const creativor = computed(() => store.state.adv.modal.creativor);
const accounts = computed(() => {
  return store.state.adv.accounts;
})

const account = computed(() => {
  return store.state.adv.accounts[0];
})



const position = computed(() => {
  return store.state.adv.modal.position;
})


const childComponent = computed(() => {
  return component.value.children || {};
})
const restriction = computed(() => {
  const image = childComponent.value.brand_image_id;
  return image ? image.restriction && image.restriction.image_restriction : {};
})


const uploadManageRef = ref();


const mainOptionalAuth = computed(() => {
  const isOnlyWxChannels = adv.value.isOnlyWxChannels;
  const medias = creativor.value.ectypeComponent['media'];
  const hasElementStory = medias[0] && medias[0].tx_component === 'element_story';
  const auth: any = {
    3: true,
    4: true,
    WECHAT_CHANNELS: true
  }
  if (isOnlyWxChannels) {
    auth[3] = false;
    auth[4] = false;
  }
  if (hasElementStory) {
    auth[4] = false;
    auth['WECHAT_CHANNELS'] = false;
  }
  return auth;
});
const mainOptionalAuthedArray = computed(() => {
  const authed:any = [];
  Object.keys(mainOptionalAuth.value).map(id => {
    if(mainOptionalAuth.value[id]) {
      authed.push(id)
    }
  });
  return authed;
})
// console.log(mainOptionalAuthedArray.value[0], 'main');
// creativor.value.brandType = mainOptionalAuthedArray.value[0];

const rules = computed(() => {
  const rules = restriction.value;

  return {
    media: {
      rect: [rules.min_width || rules.width || 500, rules.min_height || rules.height || 500],
      file_format: rules.file_format || [],
      duration: rules.min_duration || rules.max_duration ? [rules.min_duration, rules.max_duration] : [],
      suggest: rules.width || rules.height ? [rules.width, rules.height] : [],
      size: creativor.value.brandType == 4 ? rules.file_size : 50,
      ratio: rules.ratio_width ? [rules.ratio_width, rules.ratio_height] : []
    }
  }

});


const setChannelModal = reactive({
  show: false,
  currentAccount: '',
  optional: []
});


function toAuthChannel() {
  const currentAccount = setChannelModal.currentAccount
  window.open(`https://ad.qq.com/atlas/${currentAccount}/tool/wechat-channel`)
}

const wxChannelConfigStatus = computed(() => {
  const status = {
    all: accounts.value.length,
    seted: 0
  }
  accounts.value.map(account => {
    if (account.wechatChannels.id) {
      status.seted++;
    }
  });
  return status;
})


const profilesParams = computed(() => {

  return {
    action: `/api/adgroup/image/upload`,
    data: {
      accountCode: account.value ? account.value.accountCode : undefined,
      adcreativeTemplateId: creativor.value.creativeTemplateId
    }
  }
});

const profileformRef = ref();
const setProfilesModal = reactive({
  show: false,
  loading: false,
  form: {
    profileName: '',
    description: '',
    headImageId: ''
  },
  rules: {
    headImageId: {
      type: 'string',
      required: true,
      trigger: ['change'],
      message: '请上传头像'
    },
    profileName: {
      type: 'string',
      required: true,
      trigger: ['change'],
      message: '请输入名称'
    },
    description: {
      type: 'string',
      required: true,
      trigger: ['change'],
      message: '请输入详细描述'
    },
  }

})




async function closesetProfilesModal() {

  profileformRef.value.validate(async (error) => {
    if (!error) {
      setProfilesModal.loading = true;
      await addProfile({
        accountCode: account.value.accountCode,
        marketingGoal: adv.value.market.marketingGoal,
        marketingTargetType: adv.value.market.marketingTargetType,
        headImageId: setProfilesModal.form.headImageId,
        description: setProfilesModal.form.description,
        profileName: setProfilesModal.form.profileName
      })
      setProfilesModal.loading = false;
      setProfilesModal.show = false;
      changeValue(setProfilesModal.form.headImageId, {
        label: setProfilesModal.form.profileName,
        value: setProfilesModal.form.headImageId + '#MD' + setProfilesModal.form.profileName
      })
      getOptional();
    }
  })

}

function finishProfileImage(file: any) {
  setProfilesModal.form.headImageId = file.mediaId || file.media_id;
}

async function submitBrand() {
  uploadModal.loading = true;
  try {

    const info = await uploadManageRef.value.submit();
    changeValue(info.imageId, {
      label: info.name,
      value: info.image_id + '#MD' + info.name,
      url: info.image_url
    })
    getOptional();
    uploadModal.show = false;
  } catch {
    uploadModal.loading = false;

  }


}


// const wxChannelConfNum

function showSetChannel() {
  setTimeout(() => {
    setChannelModal.show = true;
    checkAccount(account.value);
  }, 300)

}

function closesetChannelModal() {
  setChannelModal.show = false;
}

function checkAccount(item: any) {
  setChannelModal.currentAccount = item.accountCode;

  getWechatChannelOptional(item);
}

function wechatChannelsFallBackOption(account: any) {
  // console.log(account, 'accou');
  return {
    value: account.wechatChannels.id,
    label: account.wechatChannels.name
  }
}


function updateWechatChannels(_: any, c: any) {
  const currentAccount = setChannelModal.currentAccount;

  const account = accounts.value.find(account => account.accountCode == currentAccount);
  if (account) {
    account.wechatChannels.id = c.value;
    account.wechatChannels.name = c.label;
    // account.wechatChannels.id = 'v2_060000231003b20faec8c7e6811fc1d1c606ed31b077e6ab3c06e2dc0d88677f7a22c438b392@finder';
  }
}

async function getWechatChannelOptional(item: any) {
  // console.log(setChannelModal.currentAccount, 'setChannelModal.currentAccount')
  const res = await getWechatChannel({
    accountCode: setChannelModal.currentAccount
  });

  if (!item.wechatChannels.optional) {
    item.wechatChannels.optional = [];

  }
  if (item.wechatChannels.optional.length) return;
  item.wechatChannels.optional = unique(res.data.map(_ => {
    return {
      label: _.wechat_channels_account_name,
      value: _.wechat_channels_account_id
    }
  }), value => value.value)
}

function changeValue(_: any, c: any) {

  form.brand_image_id = c ? c.value : undefined;
  form.brand_name = c ? c.label : undefined;
  form.brand_url = c ? c.url : undefined

  component.value.accountCode = c ? c.accountCode || account.value.accountCode : undefined;

  store.commit('adv/UPDATE_ADV_TARGET_VALUE', {
    path: ['marketComponents', props.component.type],
    key: 'value',
    value: Object.assign({}, c || {})
  })
}

const props = withDefaults(defineProps<{
  component: Component
  path: Array<any>
}>(), {});
const uploadModal = reactive<any>({
  show: false,
  uploadRules: {
    textMaxLength: 12,
    // media: {[512, 512]
  },
  formLabel: {
    input: '品牌名称'
  }

});

function toUploadBrand() {

  if (creativor.value.brandType == 3) {
    uploadModal.show = true;
    return;
  }

  setProfilesModal.show = true;
  setProfilesModal.form.headImageId = '';
  setProfilesModal.form.description = '';
  setProfilesModal.form.profileName = ''


}

const component = toRef<any, any>(props, 'component');


const form = reactive({
  brand_image_id: (component.value.joinId() || undefined),
  brand_name: component.value.value.brand_name || '',
  brand_url: component.value.value.brand_url || '',
  // switch: false,
});
watch(form, () => {
  store.commit('adv/UPDATE_ADV_TARGET_VALUE', {
    path: ['marketComponents', props.component.type],
    key: 'value',
    value: Object.assign({}, form)
  })
})
const formRule = reactive({
  ['none']: {
    required: true,
    trigger: 'change',
    validator(_, __) {
      if (!form.brand_image_id && creativor.value.brandType != 'WECHAT_CHANNELS') {
        return new Error('请选择品牌形象/品牌简介页!')
      }
      return true;
    }
  },
})

onBeforeMount(async () => {
  getOptional();
})

const optional = ref([]);
const optionalInLoad = ref(false);

function renderLabel(option: any) {
  return creativor.value.brandType == 4 ? renderProfileLabel(option) : renderBrandLabel(option);
}

function renderOption({ option }: any) {
  return h('div', {
    class: 'flex items-center',
    style: {
      padding: '10px 0'
    }
  }, [
    h(NImage, {
      src: option.url,
      fit: 'cover',
      width: 30
    }),
    h('span', {
      style: {
        marginLeft: '4px',
      }
    }, option.label)
  ])
}

const renderProfileLabel = (option: any): any => {
  return h('div', {
    class: 'flex items-center',
    style: {
      padding: '10px 0'
    }
  }, [
    h(NImage, {
      src: option.headImageUrl,
      fit: 'cover',
      width: 30
    }),
    h('span', {
      style: {
        marginLeft: '4px',

      }
    }, option.label),
    h('span', {
      class: 'flex-1 text-helper',
      style: {
        marginLeft: '30px'
      }
    }, option.headImageId ? "ID:" + option.headImageId : '')
  ])

}

const renderBrandLabel = (option: any): any => {

  return h('div', {
    class: 'flex items-center',
    style: {
      padding: '10px 0'
    }
  }, [
    h(NImage, {
      src: option.url,
      fit: 'cover',
      width: 30
    }),
    h('span', {
      style: {
        marginLeft: '4px',
      }
    }, option.label)
  ])

}




async function getOptional() {
  if (creativor.value.brandType === 'WECHAT_CHANNELS') return;
  if (account.value) {
    optionalInLoad.value = true;
    optional.value = [];
    const api = creativor.value.brandType === 4 ? getProfileList : getAdBrandList;
    const list = await api({
      accountCode: account.value.accountCode
    });
    optional.value = list.data.map((_: any) => {
      return creativor.value.brandType === 4 ? {
        // 防止重复
        ..._,
        label: _.profileName,
        value: _.headImageId + '#MD' + _.profileName,
        url: _.headImageUrl,
        accountCode: account.value.accountCode

      } : {
        ..._,
        label: _.name,
        value: _.imageId + '#MD' + _.name,
        url: _.imageUrl,
        accountCode: account.value.accountCode
      }
    });
    optionalInLoad.value = false;
  }

}


function changeBrandType() {
  form.brand_image_id = undefined;
  form.brand_name = '';

  getOptional();
  if (creativor.value.brandType == 'WECHAT_CHANNELS') {
    showSetChannel()
  }
}









</script>

<style lang="scss">
@import url('./style.scss');
</style>
<style lang="scss" scoped>
.wechat-channels-button {
  position: relative;
  --n-bezier: cubic-bezier(.4, 0, .2, 1);
  --n-arrow-height: 6px;
  --n-color: rgba(38, 38, 38, 1);

  .tooltip {
    background-color: rgba(38, 38, 38, 1);
    border-radius: 3px;
    transition: box-shadow .3s var(--n-bezier), background-color .3s var(--n-bezier), color .3s var(--n-bezier);
    position: absolute;
    font-size: 14px;
    color: #fff;
    box-shadow: 0 3px 6px -4px rgba(0, 0, 0, .12), 0 6px 16px 0 rgba(0, 0, 0, .08), 0 9px 28px 8px rgba(0, 0, 0, .05);
    word-break: break-word;
    padding: 4px 14px;
    top: -50px;
    left: -100%;

    .arrow-wrapper {
      right: 0;
      left: 0;
      top: 100%;
      bottom: auto;
      height: 10px;
      position: absolute;
      overflow: hidden;

      .arrow {
        top: calc(var(--n-arrow-height)* 1.414 / -2);
        transform: translateX(calc(var(--n-arrow-height)* 1.414 / -2)) rotate(45deg);
        left: 70px;
        transition: background-color .3s var(--n-bezier);
        position: absolute;
        display: block;
        width: calc(var(--n-arrow-height)* 1.414);
        height: calc(var(--n-arrow-height)* 1.414);
        box-shadow: 0 0 8px 0 rgba(0, 0, 0, .12);
        transform: rotate(45deg);
        background-color: var(--n-color);
        pointer-events: all;
      }
    }
  }
}
</style>
